package com.demo.List;

/**
 * @Author :蕉绿
 * @Date : 2023/2/6 10:00
 * @Version : V1.0
 * @Description :
 */
public class TestSingleList {
    //构造节点
    static class Node {
        public int val;
        public Node next;
        public Node(int val) {
            this.val = val;
        }
    }
   //存储当前头结点的引用
    public Node head;

    //创建一个链表
    public void generateList() {
        Node node1 = new Node(12);
        Node node2 = new Node(22);
        Node node3 = new Node(36);
        Node node4 = new Node(33);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        head = node1;
    }

    //打印链表
    public void display() {
        Node cur = this.head;
        while(cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
    }

    //头插法
    public void addFirst(int val) {
        Node prev = new Node(val);
        prev.next = this.head;
        this.head = prev;

    }
    //尾插法
    public void addLast(int val) {
        Node node = new Node(val);
        if(this.head == null) {
            this.head = node;
        } else {
            Node cur = this.head;
            while(cur.next != null) {
                cur = cur.next;
            }
            cur.next = node;
        }
    }


    private boolean checkIndex(int index) {
        if(index < 0 || index > size()) {
            throw new IndexNotLegalException("下标不合法!");
        }
        return true;
    }
    //任意位置插入 以第一个为 0 下标
    public void addIndex(int index,int val) {
        checkIndex(index);
        if(index == 0) {
            addFirst(val);
            return;
        }
        if(index == size()) {
            addLast(val);
            return;
        }

        Node node = new Node(val);
        Node cur = this.head;
        Node prev = this.head;
        for (int i = 0; i < index; i++) {
            prev = cur;
            cur = cur.next;
        }
        prev.next = node;
        node.next = cur;

    }

    //查找 key 并判断 key 是否存在链表中
    public boolean contains(int key) {
        Node cur = this.head;
        while(cur != null) {
            if(cur.val == key) {
                return true;
            }
            cur = cur.next;
        }
        return false;
    }
    //得到链表的长度
    public int size() {
        Node cur = this.head;
        int count = 0;
        while(cur != null) {
            count++;
            cur = cur.next;
        }
        return count;
    }


}
